<template>
  <div class="header">
        <div class="header-left fl">
           <i class="iconfont icon-shizhongclock74" style="font-size: 28px;"></i>
           <!-- 时间 -->
           <span class="time">{{ time }}</span>
           <!-- 日期 -->
           <span class="date">{{ date }}</span>
           <!-- 周末 -->
           <span class="week">{{ week }}</span>
        </div>
        <div class="header-center fl">
            <div class="header-title" >
              {{ admin_store.system_title }}
            </div>
            <div class="header-img"></div>
        </div>
        <div class="header-right fl">
         <!-- 消息 -->
            <div class="errorList" style="margin-right: 19px;" @click="openErrorList">
              <el-tooltip :content="$t('message.info')" placement="bottom" v-if="isNarrow">
            <span>
              <el-badge class="item" :value="indexDbNum" v-if="indexDbNum > 0">
                <el-icon size="20px" style="margin-right:5px;" color="#2980b9"><BellFilled /></el-icon>
              </el-badge>
              <el-icon v-else size="20px" style="margin-right:5px;" color="#2980b9"><BellFilled /></el-icon>
            </span>
          </el-tooltip>
          <span v-else class="el-dropdown-link superAdmin">
            <el-badge class="item" :value="indexDbNum" v-if="indexDbNum > 0">
              <el-icon size="20px" style="margin-right:5px;" color="#2980b9"><BellFilled /></el-icon>
            </el-badge>
            <el-icon v-else size="20px" style="margin-right:5px;" color="#2980b9"><BellFilled /></el-icon>
            <span style="font-size: 14px;">{{ $t('message.info') }}</span>
          </span>
        </div>
        <!-- 数据管理 -->
        <el-dropdown trigger="click" style="margin-right: 15px;" :popper-class="isNarrow ? 'narrow-dropdown' : ''">
            <template #default>
              <span v-if="isNarrow" class="el-dropdown-link narrow-trigger" :title="'数据管理'">
                <el-icon size="20px" style="margin-right:5px;" color="#2980b9"><DataBoard /></el-icon>
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
              <span v-else class="el-dropdown-link superAdmin">
                <el-icon size="20px" style="margin-right:5px;" color="#2980b9"><DataBoard /></el-icon>
                <span style="font-size: 14px;">数据管理</span>
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
            </template>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="toDataManage">数据列表</el-dropdown-item>
                <el-dropdown-item @click="toDataAnalysis">数据曲线</el-dropdown-item>
                <el-dropdown-item @click="openThresholdSettingDialog">阈值设置</el-dropdown-item>
                <el-dropdown-item @click="admin_store.toggleChannelEditor(true)" divided>通道名更改</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        <!-- 管理员 -->
        <el-dropdown trigger="click" :popper-class="isNarrow ? 'narrow-dropdown' : ''">
          <template #default>
            <span v-if="isNarrow" class="el-dropdown-link narrow-trigger" :title="$t('message.admin')">
              <el-icon size="20px" style="margin-right:5px;" color="#2980b9"><UserFilled /></el-icon>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <span v-else class="el-dropdown-link superAdmin">
              <el-icon size="20px" style="margin-right:5px;" color="#2980b9"><UserFilled /></el-icon>
              <span style="font-size: 14px;">{{ $t('message.admin') }}</span>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
          </template>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="toAdmin">{{ $t('message.bgMan') }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
    <!-- 报警开关 -->
    <div class="catchNormal voice-control-wrapper" style="margin-right: 0px;" :title="alarmConfig.enabled ? '点击关闭报警' : '点击开启报警'">
      <img 
        src="@/assets/images/info.png" 
        v-if="alarmConfig.enabled" 
        @click="toggleAlarmEnabled"
        class="voice-control-icon active"
        style="width:23px;height:23px;"
      />
      <img 
        src="@/assets/images/voice_forbit.png" 
        v-else 
        @click="toggleAlarmEnabled"
        class="voice-control-icon inactive"
        style="width:23px;height:23px;"
      />
    </div>
      </div>
      <div class="header-bottom fl"></div>
    </div>
  <el-dialog
      v-model="settingVisible"
      :title="$t('message.user_setting')"
      width="24%"
      draggable="true"
  >
    <el-form label-width="3rem;" :model="userSetting">
      <el-form-item :label="$t('message.data_refresh_rate')">
        <el-input-number v-model="userSetting.speed" :min="20" class="speedCss"></el-input-number>
      </el-form-item>
      <el-form-item :label="$t('message.voice_broadcast')">
        <el-switch
          v-model="isOpenVoice"
          class="mb-2"
          :active-text="$t('message.open')"
          :inactive-text="$t('message.close')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="settingVisible = false">{{ $t("message.cancel") }}</el-button>
        <el-button type="primary" @click="changeSetting">
           {{ $t("message.confirm") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
    <!-- 给传感器设置阈值 -->
    <el-dialog
      v-model="thresholdDialogVisible"
      title="阈值设置"
      width="40%"
      draggable="true"
    >
      <el-row :gutter="20">
        <el-col :span="12" v-for="item in orderList" :key="item.id" class="threshold-item">
          <div class="threshold-card">
            <h3>{{ $t(item.orderName) }}</h3>
            <div class="slider-demo-block">
              <span class="demonstration">{{$t("message.alarm")}}：</span>
              <el-slider 
                v-model="thresholdValues[item.id - 1]"
                :min="thresholdRanges[item.id - 1].min"
                :max="thresholdRanges[item.id - 1].max"
                show-input
                @change="(val) => handleThresholdChange(item.id - 1, val)"
              />
            </div>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="thresholdDialogVisible = false">{{ $t("message.cancel") }}</el-button>
          <el-button type="primary" @click="saveAllThresholds">
            {{ $t("message.confirm") }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  
  <Teleport to="body">
    <catchList></catchList>
  </Teleport>
</template>

<script lang="ts" setup>
import catchList from '../main/list.vue'
import { ref, onMounted, reactive, getCurrentInstance, inject, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { moduleStore } from '../../store/module'
import { userStore } from '../../store/user'
import { adminStore } from '../../store/admin'
import { alarmStore } from '../../store/alarm'
import { storeToRefs } from 'pinia'
import toolExports from '../../utils/tool' // 导入工具函数的默认导出对象
import { DataBoard } from '@element-plus/icons-vue'

// Access global properties
const store = inject('store') as any; // This is the global injected store
const router = useRouter();
const proxy = getCurrentInstance()!.appContext.config.globalProperties; // Assert non-null
import { WebsocketIo } from '../../utils/websocket'
const module_store = moduleStore();
const user_store = userStore();
const admin_store = adminStore();
const alarm_store = alarmStore();

const isNarrow = ref(false);
const checkWidth = () => {
  isNarrow.value = document.body.clientWidth < 1200;
};

// Destructure necessary refs from module_store
const { device_currentId, isFullscreen, isOpenVoice, alarm_type, isShowTip, setting } = storeToRefs(module_store);

// Destructure necessary refs from alarm_store
const { alarmConfig } = storeToRefs(alarm_store);

// Destructure necessary refs from user_store
const { localWebsocket, indexDbNum, userInfo } = storeToRefs(user_store);

// Destructure necessary refs from admin_store
const { isOpenDrawer } = storeToRefs(admin_store);

// Data (local refs, not from store, unless explicitly assigned)
let time = ref("");
let date = ref("");
let week = ref("");
let errList = ref([]);
let thresholdDialogVisible = ref(false);

const thresholdValues = ref<number[]>([]);
const thresholdRanges = ref<{min: number, max: number}[]>([]);


const weekList = ["message.Monday","message.Tuesday","message.Wednesday","message.Thursday","message.Friday","message.Saturday","message.Sunday"]

      // 阈值设置 
      type obj = {
        orderName: string,
        id: number,
        refName: string
      }
  const orderList:Array<obj> = [
    {
      orderName: "message.uv",
      id: 1,
      refName: "uvcRef"
    },
    {
      orderName: "message.inf",
      id: 2,
      refName: "infRef"
    },
    {
      orderName: "message.tem",
      id: 3,
      refName: "temRef"
    },  {
      orderName: "message.hum",
      id: 4,
      refName: "humRef"
    },
    {
      orderName: "message.pre",
      id: 5,
      refName: "preRef"
    }
  ]
  const handleThresholdChange = (type_id: number, value: number) => {
    console.log(`Threshold changed for type_id ${type_id}: ${value}`);
  };

  const saveAllThresholds = async () => {
    const ws = WebsocketIo.getInstance();
    for (let i = 0; i < thresholdValues.value.length; i++) {
      const currentValue = thresholdValues.value[i];
      module_store.changeValue({ id: i, currentValue: currentValue });
      if (ws.websocketIsNormal()) {
        ws.sendMessage(JSON.stringify({
          action: 'changeVal',
          module_id: device_currentId.value,
          type_id: i,
          errorVal: currentValue
        }));
      }
    }
    proxy.$message({ showClose: true, message: "所有阈值已保存", type: "success" });
    thresholdDialogVisible.value = false;
  };
    const toAdmin = ():void => {
        router.push("/admin")
    }
    
    // 跳转到数据管理页面
    const toDataManage = ():void => {
        router.push("/admin/data")
    }
    
    // 跳转到数据分析页面
    const toDataAnalysis = ():void => {
        router.push("/admin/analysis")
    }
    

    const emit = defineEmits(['resetData','closeTimer','startTimer',"taggleDevice","resetView"])
    let userSetting:{speed:number} = reactive({
      speed: store?.speed || 20 // 添加默认值 20，并使用可选链操作符
    })

    import indexDb from '../../local/indexDb'
    
    onMounted(() => {
      checkWidth();
      window.addEventListener("resize", checkWidth);
      setInterval(() => {
        let date1 = new Date()
        time.value = date1.toLocaleTimeString()
        date.value = date1.toLocaleDateString().replace(/\//g,"-")
        week.value = proxy.$t(weekList[(date1.getDay() + 6) % 7])
      },1000)

        // 同步语音报警状态
  const syncVoiceAlarmStatus = () => {
    if (alarm_store && alarm_store.alarmConfig) {
      // 根据alarm store的状态更新UI
      if (alarm_store.alarmConfig.voiceEnabled) {
        alarm_type.value = 1;
        isShowTip.value = true;
      } else {
        alarm_type.value = 2;
        isShowTip.value = false;
      }
    }
  };
  
  // 初始化时同步状态
  syncVoiceAlarmStatus();
  
  // 监听alarm store变化
  if (alarm_store && alarm_store.$subscribe) {
    alarm_store.$subscribe((mutation, state) => {
      if (mutation.storeId === 'alarm' && mutation.events?.key === 'voiceEnabled') {
        syncVoiceAlarmStatus();
      }
    });
  }
    })
    // 修改报警的状态值
    const changeWarningStatus = () => {
      try {
      if (alarm_type.value == 1) {
            alarm_type.value = 2
            isShowTip.value = false
          
          // 关闭语音时，立即停止当前语音播报并清空队列
          if (window.speechSynthesis) {
            window.speechSynthesis.cancel();
          }
          
          // 同步更新报警Worker配置
          const alarmWorkerInstance = (window as any).__alarmWorker || store?.alarmWorker;
          if (alarmWorkerInstance) {
            // 监听worker发来的停止语音消息
            alarmWorkerInstance.addEventListener('message', (event: MessageEvent) => {
              if (event.data.type === 'stop_speech') {
                if (window.speechSynthesis) {
                  window.speechSynthesis.cancel();
                }
              }
            });
            // 清空语音队列
            alarmWorkerInstance.postMessage({
              type: 'clear_voice_queue'
            });
            // 更新配置
            alarmWorkerInstance.postMessage({
              type: 'update_config',
              data: { voiceEnabled: false }
            });
          }
          
          // 同步更新alarm store
          if (alarm_store) {
            alarm_store.alarmConfig.voiceEnabled = false;
          }
          
          proxy.$message({
            message: "语音报警已关闭",
            type: "info",
            duration: 2000
          });
          
        } else if(alarm_type.value == 2) {
          alarm_type.value = 1
          isShowTip.value = true
          
          // 同步更新报警Worker配置
          const alarmWorkerInstance = (window as any).__alarmWorker || store?.alarmWorker;
          if (alarmWorkerInstance) {
            alarmWorkerInstance.postMessage({
              type: 'update_config',
              data: { voiceEnabled: true }
            });
          }
          
          // 同步更新alarm store
          if (alarm_store) {
            alarm_store.alarmConfig.voiceEnabled = true;
          }
          
          proxy.$message({
            message: "语音报警已开启",
            type: "success",
            duration: 2000
          });
        }
        } catch (error) {
          console.log(error);
        }
}
    const openThresholdSettingDialog = () => {
      if (setting.value && Array.isArray(setting.value) && setting.value[0]) {
        const settings = setting.value[0];
        thresholdValues.value = settings.map((s: any) => s.current_val);
        thresholdRanges.value = settings.map((s: any) => ({ min: s.normal_low, max: s.normal_high }));
        thresholdDialogVisible.value = true;
      } else {
        proxy.$message.warning("阈值设置数据缺失或尚未加载");
      }
    };

    onUnmounted(() => {
      window.removeEventListener('resize', checkWidth);
    });

    const toggleAlarmVoice = () => {
      alarm_store.toggleVoiceAlert();
    };

    // 全屏显示页面
    const taggleFullscreen = () => {
      if (!isFullscreen.value) {
         toolExports.launchFullscreen(document.documentElement) // Use toolExports
         isFullscreen.value = true
      } else {
          toolExports.exitFullscreen() // Use toolExports
          isFullscreen.value = false
      }
    }
      // 打开报警列表
      const openErrorList = async () => {
        if (!indexDbNum.value) return proxy.$message.info("暂无报警信息")
        isOpenDrawer.value = true
        let result:any = await indexDb.getAllData()
        errList.value = result.slice(0,10)
    }
 
    // 新增：报警开关切换
    const toggleAlarmEnabled = () => {
      alarmConfig.value.enabled = !alarmConfig.value.enabled;
      
      // 如果关闭报警，立即停止语音播报并清空队列
      if (!alarmConfig.value.enabled) {
        // 停止当前语音播报
        if (window.speechSynthesis) {
          window.speechSynthesis.cancel();
        }
        
        // 通知 alarmWorker 清空语音队列
        const alarmWorkerInstance = (window as any).__alarmWorker || store?.alarmWorker;
        if (alarmWorkerInstance) {
          alarmWorkerInstance.postMessage({
            type: 'clear_voice_queue'
          });
        }
      }
      
      // 通知 alarmWorker 更新配置
      if ((window as any).__alarmWorker) {
        (window as any).__alarmWorker.postMessage({
          type: 'update_config',
          data: { 
            enabled: alarmConfig.value.enabled,
            voiceEnabled: alarmConfig.value.enabled ? alarmConfig.value.voiceEnabled : false
          }
        });
      }
      
      proxy.$message({
        message: alarmConfig.value.enabled ? '报警已开启' : '报警已关闭',
        type: alarmConfig.value.enabled ? 'success' : 'info',
        duration: 2000
      });
    }
 

</script>

<style lang="less" scoped>
.alarm-voice-control {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-right: 15px;
}

.threshold-item {
  margin-bottom: 20px;
}

.threshold-card {
  border: 1px solid #409EFF;
  border-radius: 4px;
  padding: 15px;
  background-color: #f0faff;
}

.threshold-card h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
}

.slider-demo-block {
  display: flex;
  align-items: center;
}

.slider-demo-block .demonstration {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  line-height: 44px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 0;
}

.slider-demo-block .demonstration + .el-slider {
  flex: 0 0 70%;
}

.fl {
    float: left;
}
.speedCss {
  width: 160px;
}

// 头部的一些样式
.header {
    width: 100%;
    height: 60PX;
    background-image: linear-gradient(to bottom, #20427a, #10152b);
   .header-left {
    width: 30%;
    height: 55PX;
    color: white;
    display: flex;
    align-items: center;
    padding-left: 10px;
    padding-top: 10px;
    span {
      margin-right: 10px;
    }
    .time {
      margin-left: 10px;
      font-size: 20px;
    }
     .el-icon {
       font-weight: bold;
     }
}
.header-center {
    width: 40%;
    height: 55PX;
    /* border: 1px solid red; */
    position: relative;
    .header-title {
    text-align: center;
    color: #ffffff;
    font-size: 28px;
    text-shadow: 0 0 4px #00d8ff;
    line-height: 30px;
    padding: 5px 0px;
}
 .header-img {
    background: url(@/assets/images/head.gif) no-repeat center center;
    background-size: 100%;
    height: 100%;
    width: 100%;
    position: absolute;
    top: 23px;
}
}
.header-right {
    width: 30%;
    height: 55PX;
    line-height: 80px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: #fff;
    padding-right: 5px;
    font-size: 15px;
    .errorList {
      height: 50px;
      .superAdmin {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 15px;
        .el-badge {
          height: 30px;
          display: flex;
          align-items: center;
        }
      }
    }
    .setting {
      display: flex;
      align-items: center;
      margin-right: 20px;
      font-size: 14px;
      img {
        width: 25px;
        height: 20px;
        margin-right: 10px;
      }
    }
  
    .el-dropdown {
      height: 30px;
      border: none!important;
      .el-dropdown-link {
        display: flex;
        align-items: center;
        color: #fff;
        cursor: pointer;
        &:hover{
        border: none;
        }
      }
      .narrow-trigger {
        display: flex;
        align-items: center;
        color: #fff;
        cursor: pointer;
        padding: 5px;
        border-radius: 4px;
        transition: background-color 0.3s;
        &:hover {
          background-color: rgba(255, 255, 255, 0.1);
        }
      }
    }
    .fullscreen {
      width: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      margin-right: 10px;
    }
}
.header-bottom {
    width: calc(100% - 8px);
    height: 5PX;
    background: url(@/assets/images/header.png) no-repeat;
    background-size: calc(100% - 3px) 100%;
    padding: 0 3px;
    margin-left: 3px;
}
}

// 菜单样式
.menu {
        width: 100%;
        list-style: none;
        display: flex;
        line-height: 60px;
        a {
            color: #fff;
            flex:1;
            background: url("@/assets/images/bnt.png") no-repeat center;
            display: flex;
            justify-content: center;
            text-decoration: none;
        }
}

.drawer-main {
  height: 400px;
  display: grid;
  grid-template-columns: repeat(4,1fr);
  grid-template-rows: repeat(4,1fr);
  .module_item {
    display: flex;
    flex-direction: column;
    .img {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 70px;
        height: 70px;
      }
    }
    p {
      height: 30px;
      width: 100%;
      text-align: center;
    }
  }
}
.module_list {
  height: 300px;
  display: grid;
  grid-template-columns: repeat(6,1fr);
  grid-template-rows: repeat(4,1fr);
  .module_item {
    display: flex;
    flex-direction: column;
    .img {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 40px;
        height: 40px;
      }
    }
    p {
      height: 30px;
      width: 100%;
      text-align: center;
    }
  }
}
.catchNormal {
  padding-left: 15px;
  padding-right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    width: 20px;
    height: 20px;
    &:hover {
      cursor: pointer;
    }
  }
}
.voice-control-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    opacity: 0.8;
  }
  
  .voice-control-icon {
    width: 22px;
    height: 22px;
    transition: all 0.3s ease;
    
    &.active {
      filter: brightness(1.2);
    }
    
    &.inactive {
      filter: grayscale(0.5);
    }
  }
  
}

// 小屏幕下拉菜单样式
:deep(.narrow-dropdown) {
  z-index: 9999 !important;
}

:deep(.el-dropdown-menu) {
  z-index: 9999 !important;
  min-width: 120px;
}

// 确保下拉菜单在小屏幕下正常显示
@media (max-width: 1000px) {
  :deep(.el-dropdown-menu) {
    position: fixed !important;
    z-index: 9999 !important;
  }
}
:deep(.el-badge__content.is-fixed) {
  top: 5px;
}
</style>